package com.laosg.oauth2.authresourceserver.controller;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

@Controller
public class LoginController {

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/index")
    public String index() {
        return "index";
    }

    /**
     * 可以完成统一登出的步骤
     * @param request
     * @param response
     */

    @RequestMapping("/logout")
    public void exit(HttpServletRequest request, HttpServletResponse response) {
        // token can be revoked here if needed
        new SecurityContextLogoutHandler().logout(request, null, null);
        try {
            //sending back to client app
            response.sendRedirect(request.getHeader("referer"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//    @GetMapping("/oauth/confirm_access")
    public String confirmAccess(HttpSession session, Map<String, Object> model, HttpServletRequest request) {
        //在这里推荐使用AuthorizationRequest来获取scope
        AuthorizationRequest authorizationRequest = (AuthorizationRequest) session.getAttribute("authorizationRequest");

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        model.put("auth", authentication);
        Set<String> scope = authorizationRequest.getScope();
        model.put("scopeList", scope);
        model.put("clientId", authorizationRequest.getClientId());
        return "confirm_access_1";
    }


}
